package com.snail.permission.bridge;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

/**
 * @author zhaoyan
 * @date 2019-03-18
 */
class Messenger extends BroadcastReceiver {

    private static final String ACTION = "com.snail.permission.bridge";
    private final Context mContext;
    private final Callback mCallback;
    private boolean mReceiverTag = false;

    public Messenger(Context context, Callback callback) {
        this.mContext = context;
        this.mCallback = callback;
    }

    public static void send(Context context) {
        Intent broadcast = new Intent(ACTION);
        context.sendBroadcast(broadcast);
    }

    public Context getContext() {
        return mContext;
    }

    public void register() {
        if (!mReceiverTag) {
            mReceiverTag = true;
            IntentFilter filter = new IntentFilter(ACTION);
            mContext.registerReceiver(this, filter);
        }
    }

    public void unRegister() {
        if (mReceiverTag) {
            mReceiverTag = false;
            try {
                mContext.unregisterReceiver(this);
            } catch (IllegalArgumentException e) {
                Log.d("zhaoyan97", "unRegister e = " + e.getMessage());
                if (e.getMessage().contains("Receiver not registered")) {
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        mCallback.onCallback();
    }

    public interface Callback {

        void onCallback();
    }
}